package com.dxy.yesas2020goals.study.partone.disignpattern.cmdpattern.ftp;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class FtpTools {

	public static final long KB = 1024;
	public static final long MB = 1024 * KB;
	public static final long GB = 1024 * MB;

	// 取以空格分界的子字符串，index基于1
	public static String SubStr(String str, int index) {
		if (index < 1)
			index = 1; // index基于1

		int ls = str.length();
		int i = 0, j = 0, times = 0;

		str += ' ';
		do {
			i = j;
			while (str.charAt(i) == ' ' && i < ls)
				i++;
			j = i;
			while (str.charAt(j) != ' ' && j < ls)
				j++;

			times++;
		} while (times != index && i < ls);

		return str.substring(i, j);
	}

	// 取以空格分界的子字符串的起始位置，index基于1，返回值基于0
	public static int SubStrPos(String str, int index) {
		if (index < 1)
			index = 1; // index基于1

		int ls = str.length();
		int i = 0, j = 0, times = 0;

		str += ' ';
		do {
			i = j;
			while (str.charAt(i) == ' ' && i < ls)
				i++;
			j = i;
			while (str.charAt(j) != ' ' && j < ls)
				j++;

			times++;
		} while (times != index && i < ls);

		return i;
	}

	public static String left(String str, int l) {
		int lstr = str.length();
		if (lstr < l)
			return str;
		return str.substring(0, l);
	}

	// 取右端子字符串
	public static String right(String s, int l) {
		int ls = s.length();
		if (ls <= l)
			return s;
		return s.substring(ls - l, ls);
	}

	// 字符串替换
	public static String replace(String str, String oldstr, String newstr) {
		StringBuffer result = new StringBuffer();
		int lstr = str.length();
		int loldstr = oldstr.length();

		int p = 0;
		int off0 = 0, off1;
		while (p <= lstr - loldstr) {
			off1 = off0;
			do {
				if (str.charAt(p + off1) == oldstr.charAt(off1))
					off1 = (off1 + 1) % loldstr;
				else {
					off0 = off1++;
					break;
				}
			} while (off1 != off0);

			if (off1 == off0) // 替换
			{
				result.append(newstr);
				p += loldstr;
			} else
				// 下一字符
				result.append(str.charAt(p++));
		}
		// 剩下的字符
		while (p < lstr)
			result.append(str.charAt(p++));

		return result.toString();
	}

	// 修正目录：去掉/./，中和/../，修正//、\\，\等
	public static String fmtDir(String dir) {
		if (dir.length() == 0)
			dir = "/";
		dir = replace(dir, "\\", "/");

		String drive = "";
		if (dir.length() >= 2) {
			drive = dir.substring(0, 2);
			if (dir.charAt(1) == ':') // drive.equals("//") 被取消
				dir = dir.substring(2);
			else
				drive = "";
		}

		if (dir.length() == 0)
			dir = "/";
		dir = replace(dir, "//", "/");
		if (dir.charAt(dir.length() - 1) != '/')
			dir += "/";
		dir = replace(dir, "/./", "/");

		int p;
		while ((p = dir.indexOf("/../")) >= 0) {
			if (p > 0) {
				int pup;
				if ((pup = dir.substring(0, p).lastIndexOf('/')) >= 0)
					dir = dir.substring(0, pup) + dir.substring(p + 3);
				else
					dir = dir.substring(p + 3);
			} else
				dir = dir.substring(3);
		}

		return drive + dir;
	}

	public static String fmtPath(String currDir, String strPath) {
		String tmpPath = "/" + strPath;
		if (right(tmpPath, 3).equals("/..") || right(tmpPath, 2).equals("/."))
			strPath += "/";

		if (strPath.length() <= 0)
			tmpPath = currDir;
		else if (strPath.charAt(0) == '/')
			tmpPath = strPath;
		else
			tmpPath = currDir + strPath;

		int pd = tmpPath.lastIndexOf('/');
		if (pd < 0)
			return strPath;
		else
			return fmtDir(tmpPath.substring(0, pd + 1)) + tmpPath.substring(pd + 1);
	}

	/**
	 * 删除目录
	 * 
	 * @param file
	 */
	public static boolean deleteDir(File file) {
		try {
			if (file.isFile() || file.list().length == 0) {
				file.delete();
			} else {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteDir(files[i]);
					files[i].delete();
				}
				if (file.exists())
					file.delete();
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static Date StringToDate(String dateStr, String formatStr) {
		DateFormat dd = new SimpleDateFormat(formatStr);
		Date date = null;
		try {
			date = dd.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	private final static String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

	public final static String getUnixDate(long millis) {
		if (millis < 0) {
			return "------------";
		}

		StringBuilder sb = new StringBuilder(16);
		Calendar cal = new GregorianCalendar();
		cal.setTimeInMillis(millis);

		// month
		sb.append(MONTHS[cal.get(Calendar.MONTH)]);
		sb.append(' ');

		// day
		int day = cal.get(Calendar.DATE);
		if (day < 10) {
			sb.append(' ');
		}
		sb.append(day);
		sb.append(' ');

		long sixMonth = 15811200000L; // 183L * 24L * 60L * 60L * 1000L;
		long nowTime = System.currentTimeMillis();
		if (Math.abs(nowTime - millis) > sixMonth) {

			// year
			int year = cal.get(Calendar.YEAR);
			sb.append(' ');
			sb.append(year);
		} else {

			// hour
			int hh = cal.get(Calendar.HOUR_OF_DAY);
			if (hh < 10) {
				sb.append('0');
			}
			sb.append(hh);
			sb.append(':');

			// minute
			int mm = cal.get(Calendar.MINUTE);
			if (mm < 10) {
				sb.append('0');
			}
			sb.append(mm);
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		/*List<String> cookies = new ArrayList<String>();
		cookies.add("userinfo={\"uid\":1,\"uname\":\"test@qq.com\",\"schoolID\":1,\"title\":\"leovs\",\"utype\":0}; userkey=9da320a3d161647bc0527c448955296e");
		System.out.println(WebServer.getFile(cookies, "path"));*/
		System.out.println(System.getProperty("os.name"));
		System.out.println(new File("D:\\ftptest\\test\\qq\\com\\test@qq.com\\新建文件夹").renameTo(new File("D:\\ftptest\\test\\qq\\com\\test@qq.com\\新建文件夹21")));
	}
}
